/*
 * @Author: HeAo
 * @Date: 2021-11-02 09:25:01
 * @LastEditTime: 2021-11-03 09:14:49
 * @LastEditors: HeAo
 * @Description:
 * @FilePath: \web2103-2105\web2103code\4-1-Nodejs\day03\1-http.js
 * 别乱动！
 */
let http = require('http');
let url = require('url');
let qs = require('querystring');

// 封装响应结果
class Response {
  constructor(message, data) {
    this.message = message
    this.data = data
    this.status = 20000
    this.timestamp = new Date().getTime()
  }
}


http.createServer((req, res) => {
  // http://localhost:3000/user/findAll
  // 处理前端请求地址，判断业务需求
  const urlObj = url.parse(req.url)
  switch (urlObj.pathname) {
    case '/user/findAll':
      const users = [
        { id: 1, name: 'terry', age: 12 },
        { id: 2, name: 'larry', age: 12 },
        { id: 3, name: 'tom', age: 12 },
      ]
      // 设置响应行的状态码以及状态信息，响应头
      res.writeHead(200, 'SUCCESS', {
        'Content-Type': 'application/json'
      })
      // 设置响应体
      res.write(JSON.stringify(new Response('查询成功', users)))
      res.end()
      break;
    case '/user/deleteById':
      const id = qs.parse(urlObj.query).id
      // 设置响应头
      res.writeHead(200, {
        'Content-Type': 'application/json'
      })
      // 设置响应体
      res.write(JSON.stringify(new Response('删除成功', null)))
      res.end()
      break;
    case '/user/saveOrUpdate':
      req.on('data', (chunk) => {
        let data = qs.parse(chunk.toString())
        if (data.id) {
          res.write(JSON.stringify(new Response('修改成功', null)))
          res.end()
        } else {
          res.write(JSON.stringify(new Response('保存成功', null)))
          res.end()
        }
      })
      break;
    default:
      res.write('找不到该资源')
      break;
  }

  // /user/findAll
  // /user/deleteById
  // /user/saveOrUpdate
  // /user/findById

}).listen('3000', () => {
  console.log('server is running');
})





